package service;

import bean.Docs;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import util.FileUtils;
import util.RequestUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;


/**
*@ClassName: DownloadService
*@Description: word 下载
*@Params: 
*@Return: 
*@Author xxw
*@Date 2021/12/24
*/
public class DownloadService {
    private static String SAVE_PATH = ""; // word导出位置
    private static CloseableHttpClient httpClient; // http 对象
    private static String cookieTextUrl = "cookie.txt";
    private static String cookie = ""; // 请求 cookie
    public static final int cache = 10 * 1024; // 设置缓冲区大小
    // 静态代码块
    static {
        DownloadService.cookie = FileUtils.readFile(cookieTextUrl);
        try {
            DownloadService.httpClient =  RequestUtils.getHttpClient();
        } catch (Exception e) {
            System.out.println("word ---> http对象创建失败! ");
        }
    }
    // 下载word
    public void downloadWord(ArrayList<Docs> list, ExecutorService executorService, String path){
        DownloadService.SAVE_PATH = path;
        // 建立文件夹
        try {
            File dir = new File(SAVE_PATH);
            if (!dir.isDirectory()) {
                dir.mkdir();
            }
        } catch (Exception e) {
            System.out.println("文件夹创建有误");
        }
        System.out.println("开始多线程下载文件（线程为 10）....");
        System.out.println("================================");
        for (int i = 0; i < list.size(); i++) {
            // 不是为 null 则发送请求
            String docsDowUrl = list.get(i).getDocsDowUrl();
            if (!docsDowUrl.equals("null")) {
                HttpGet httpGet = new HttpGet(docsDowUrl);
                // 请求头定义
                httpGet.setHeader("Cookie", cookie);
                // 发送请求
                CloseableHttpResponse response = null;
                try {
                    response = httpClient.execute(httpGet);
                } catch (IOException e) {
                    System.out.println("word --> CloseableHttpResponse 出现异常！");
                }
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 获取流
                InputStream content = null;
                try {
                    content = entity.getContent();
                } catch (IOException e) {
                    System.out.println("InputStream对象创建出现异常！");
                }
                // 多线程写入
                int finalI = i;
                InputStream finalContent = content;
                executorService.execute(() -> {
                    System.out.println(list.get(finalI).getFilename() + ".md 文件正在写入... ");
                    // 创建文件 && 写入
                    File file = new File(SAVE_PATH + list.get(finalI).getFilename() + ".md");
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            System.out.println("创建 "+ list.get(finalI).getFilename() +".md 文件失败！");
                        }
                    }
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(file);
                    } catch (FileNotFoundException e) {
                        System.out.println("FileOutputStream对象创建异常！");
                    }
                    byte[] buffer = new byte[cache];
                    int ch = 0;
                    try {
                        while ((ch = finalContent.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0 ,ch);
                        }
                    } catch (Exception e) {
                        System.out.println("read 出现异常！");
                    } finally {
                        try {
                            finalContent.close();
                            fileOutputStream.flush();
                            fileOutputStream.close();
                            System.out.println(list.get(finalI).getFilename() + ".md 文件写入完成！ ");
                        }catch (Exception e) {
                            System.out.println("IO 关闭出现异常！");
                        }
                    }
                });
            }
        }
        try {
            Thread.sleep(3000);
            System.out.println("================================");
            System.out.println("文件已全部下载完成！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
